const { ipcRenderer } = require('electron');

class PrintServiceApp {
    constructor() {
        this.isServiceRunning = false;
        this.timeInterval = null;
        this.init();
    }

    async init() {
        this.bindEvents();
        this.updateUI();
        this.checkServiceStatus();

        try {
            const printerName = await ipcRenderer.invoke('get-default-printer');
            document.getElementById('defaultPrinterName').textContent = printerName;
        } catch (error) {
            console.error('获取默认打印机名字失败:', error);
        }
    }

    bindEvents() {
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const testPrinterBtn = document.getElementById('testPrinter');

        startBtn.addEventListener('click', () => this.startService());
        stopBtn.addEventListener('click', () => this.stopService());
        testPrinterBtn.addEventListener('click', () => this.testPrinter());
    }

    async startService() {
        try {
            this.addLog('正在启动服务...');
            const result = await ipcRenderer.invoke('start-service');
            
            if (result.success) {
                this.isServiceRunning = true;
                this.updateUI();
                this.startTimeDisplay();
                this.addLog('✅ ' + result.message);
            } else {
                this.addLog('❌ ' + result.message);
            }
        } catch (error) {
            this.addLog('❌ 启动服务失败: ' + error.message);
        }
    }

    async stopService() {
        try {
            this.addLog('正在停止服务...');
            if (!this.isServiceRunning) {
                this.addLog('⚠️ 服务未运行，无需停止');
                return;
            }
            const result = await ipcRenderer.invoke('stop-service');
            
            if (result.success) {
                this.isServiceRunning = false;
                this.updateUI();
                this.stopTimeDisplay();
                this.addLog('⏹️ ' + result.message);
            } else {
                this.addLog('❌ ' + result.message);
            }
        } catch (error) {
            this.addLog('❌ 停止服务失败: ' + error.message);
        }
    }

    async checkServiceStatus() {
        console.log('检查服务状态...');
        try {
            const status = await ipcRenderer.invoke('get-service-status');
            this.isServiceRunning = status;
            this.updateUI();
            
            if (this.isServiceRunning) {
                this.startTimeDisplay();
            }
        } catch (error) {
            console.error('检查服务状态失败:', error);
        }
    }

    updateUI() {
        const startBtn = document.getElementById('startBtn');
        const stopBtn = document.getElementById('stopBtn');
        const statusText = document.getElementById('statusText');
        const statusDot = document.querySelector('.status-dot');

        if (this.isServiceRunning) {
            startBtn.disabled = true;
            stopBtn.disabled = false;
            statusText.textContent = '服务运行中';
            statusDot.classList.add('active');
            
            // 更新按钮样式
            startBtn.style.opacity = '0.5';
            stopBtn.style.opacity = '1';
        } else {
            startBtn.disabled = false;
            stopBtn.disabled = true;
            statusText.textContent = '服务已停止';
            statusDot.classList.remove('active');
            
            // 更新按钮样式
            startBtn.style.opacity = '1';
            stopBtn.style.opacity = '0.5';
        }
    }

    startTimeDisplay() {
        this.updateTime();
        this.timeInterval = setInterval(() => {
            this.updateTime();
        }, 1000);
    }

    stopTimeDisplay() {
        if (this.timeInterval) {
            clearInterval(this.timeInterval);
            this.timeInterval = null;
        }
        document.getElementById('currentTime').textContent = '--:--:--';
    }

    updateTime() {
        const now = new Date();
        const timeString = now.toLocaleTimeString('zh-CN', { 
            hour12: false 
        });
        document.getElementById('currentTime').textContent = timeString;
    }

    addLog(message) {
        const logContent = document.getElementById('logContent');
        const logItem = document.createElement('div');
        logItem.className = 'log-item';
        
        const timestamp = new Date().toLocaleTimeString('zh-CN');
        logItem.innerHTML = `<span class="log-time">[${timestamp}]</span> ${message}`;
        
        logContent.appendChild(logItem);
        logContent.scrollTop = logContent.scrollHeight;
        
        // 限制日志数量，避免内存占用过多
        const logItems = logContent.querySelectorAll('.log-item');
        if (logItems.length > 4) {
            logItems[0].remove();
        }
    }

    async testPrinter() {
        try {
            this.addLog('正在请求测试打印...');
            const result = await ipcRenderer.invoke('test-printer');
            if (result.success) {
                this.addLog('✅ ' + result.message);
            } else {
                this.addLog('❌ ' + result.message);
            }
        } catch (error) {
            this.addLog('❌ 测试打印失败: ' + error.message);
        }
    }
    
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.printServiceApp = new PrintServiceApp();
});

// 监听窗口关闭事件
window.addEventListener('beforeunload', () => {
    // 清理定时器
    if (window.printServiceApp && window.printServiceApp.timeInterval) {
        clearInterval(window.printServiceApp.timeInterval);
    }
});